import telebot
import json
import sys
import re


class BotInfo:
    def __init__(self):
        with open('botinfo.json') as botdata:
            self.botdata = json.load(botdata)

    def save(self):
        with open('botinfo.json', 'w') as json_file:
            json.dump(self.botdata, json_file)


note = BotInfo()
for i in range(0, len(sys.argv)):
    if sys.argv[i] == '-admin':
        if sys.argv[i+1] in note.botdata['admins']:
            note.botdata['admins'].remove(sys.argv[i+1])
            print(f'Delete user: {sys.argv[i+1]}')
        else:
            note.botdata['admins'].append(sys.argv[i+1])
            print(f'New user: {sys.argv[i+1]}')
    elif sys.argv[i] == '-token':
        note.botdata['token'] = sys.argv[i+1]
bot = telebot.TeleBot(note.botdata["token"])
note.save()


@bot.message_handler(commands=['start', 'help'])
def tutorial(message):
    bot.send_message(message.chat.id, "Бот сделан на основе EasyBot v0.1")


@bot.message_handler(commands=['bad'])
def censorship(message):
    note = BotInfo()
    for word in message.text.split()[1::]:
        if word.lower() not in note.botdata["bad-words"]:
            note.botdata["bad-words"].append(word.lower())
        else:
            note.botdata["bad-words"].remove(word.lower())
    note.save()


@bot.message_handler(commands=['badlist'])
def censorlist(message):
    with open('botinfo.json') as botread:
        content = '\n'.join([word for word in json.load(botread)["bad-words"]])
        if content:
            bot.send_message(message.chat.id, content)


@bot.message_handler(commands=['add'])
def add_action(message):
    note = BotInfo()
    argument = message.text[5::].split(':')
    if argument[0] not in note.botdata["actions"]:
        note.botdata["actions"].update({argument[0]:argument[1]})
    else:
        note.botdata["actions"].pop(argument[0])
    note.save()


@bot.message_handler()
def group(message):
    if message.chat.title:
        note = BotInfo()
        for word in note.botdata["bad-words"]:
            if re.findall(f'\\b{word.lower()}\\b', message.text.lower()):
                bot.delete_message(message.chat.id, message.message_id)
                break
        else:
            if message.reply_to_message:
                for action in note.botdata["actions"]:
                    if re.findall(f'\\b{action.lower()}\\b', message.text.lower()):
                        bot.send_message(message.chat.id, note.botdata["actions"][action])
                        break
                note.save()


bot.polling()
